<script setup lang="ts">
import {onMounted, ref, reactive} from "vue";
import myAxios from "../../plugins/my-axios.ts";
import {ArrowRight, Delete, Edit, Search} from "@element-plus/icons-vue";
import {FormRules} from "element-plus";
import {ElMessage, ElMessageBox} from 'element-plus'

const currentPage = ref(1)
const title = ref("")
const pageSize = ref(0)
const total = ref(0)
const tableBlogData = ref([])
const searchBlogname = ref('')
const addUserFormVisible = ref(false)
const beforeBanBlogFormVisible = ref(false)
const formLabelWidth = '140px'
const updateBlogFormVisible = ref(false)
const userInfoFormVisible = ref(false)
const blogInfoFormVisible = ref(false)
onMounted(async () =>{
  await handleSearch()
})
const researchBlog = () => {
  handleSearch()
}

const beforeBanBlogForm = ref({
  id: '',
})

const handleCurrentChange = async () => {
  tableBlogData.value = []
  const url = "/blog/select?currentPage=" + currentPage.value + "&title=" + searchBlogname.value
  let res = await myAxios.get(url);
  console.log(res)
  if (res?.data.code === 0) {

    res.data.data.records.forEach(blog => {
      blog.userStatus = blog.userStatus == 0 ? '正常' : '封禁'
      // blog.userStatus = blog.userStatus == 0 ? '正常' : '封禁'
      tableBlogData.value.push(blog)
    })
    currentPage.value = res.data.data.current
    pageSize.value = res.data.data.size
    total.value = res.data.data.total
    console.log(tableBlogData)
  }

}
const confirmDelete = (id: string) => {
  ElMessageBox.confirm(
      '此操作无法撤销',
      '确认删除用户',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        let res = await myAxios.delete(`/blog/${id}`);
        if (res.data.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          await handleSearch()
        } else {
          ElMessage.error(res.data.description)
        }
      })
}


const handleSearch = async () => {
  tableBlogData.value = []
  currentPage.value = 1
  // let res = await myAxios.get("/blog/list?username=" + searchBlogname.value + "&currentPage=" + currentPage.value);
  let res = await myAxios.get("/blog/select?currentPage=" + currentPage.value + "&title=" + searchBlogname.value);
  if (res?.data.code === 0) {
    res.data.data.records.forEach(blogitem => {
      blogitem.userStatus = blogitem.userStatus == 0 ? '正常' : '封禁'
      blogitem.isban = blogitem.isban == 0 ? '正常' : '封禁'
      tableBlogData.value.push(blogitem)
    })
    currentPage.value = res.data.data.current
    pageSize.value = res.data.data.size
    total.value = res.data.data.total
  }
}

const addBlogForm = reactive({
  title: '',
  content: ''
})
const updateBlogForm = ref({
  username: '',
  title: '',
  isban: '',
  content: ''
})

interface RuleForm{
  title: string,
  content: string
}

const addBlogFormRoles = reactive<FormRules<RuleForm>>({
  title: [
    {required: true,message:'请输入标题', trigger: 'blur'}
  ],
  content: [
    {required: true,message:'请输入内容', trigger: 'blur'}
  ]

})

const getBlogInfo = async (id: string) => {
  let res = await myAxios.get("/blog/" + id);
  if (res.data.code === 0) {
    updateBlogFormVisible.value = true

  } else {
    ElMessage.error(res.data.description)
  }
}


const handleUpdateBlog = async () => {
  const userData = {
    username: updateBlogForm.value.username,
    title: updateBlogForm.value.title,
    content: updateBlogForm.value.content,
  }
  let res = await myAxios.put("/blog/admin/update", userData);
  if (res.data.code === 0) {
    updateBlogFormVisible.value = false
    ElMessage({
      message: '用户更新成功',
      type: 'success',
    })
    await handleSearch()
  } else {
    ElMessage.error(res.data.description)
  }
}

const banBlog = async (id: number) => {
  let res = await myAxios.get("/blog/ban?id=" + id);
  if (res.data.code === 0) {
    ElMessage({
      message: '用户封禁/解禁成功',
      type: 'success',
    })
    blogInfoFormVisible.value = false
    await handleSearch()
  } else {
    ElMessage.error(res.data.description)
  }
}

const searchedBlog = ref({
  title: '',
  content: '',
  images: ''
})

const searchBlog = async (id: string) => {
  let res = await myAxios.get("/blog/" + id);
  console.log(res)
  if (res.data.code === 0) {
    beforeBanBlogFormVisible.value = false
    blogInfoFormVisible.value = true
    searchedBlog.value = res.data.data
  } else {
    ElMessage.error(res.data.description)
  }
}


</script>

<template>
  <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: '/blog' }">文章管理</el-breadcrumb-item>
  </el-breadcrumb>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input placeholder="请输入内容" v-model="searchBlogname" clearable @change="researchBlog">
          <template #append>
            <el-button :icon="Search" @click="handleSearch"/>
          </template>
        </el-input>
      </el-col>
<!--      <el-col :span="2">-->
<!--        <el-button type="primary" @click="addUserFormVisible = true">添加用户</el-button>-->
<!--      </el-col>-->
            <el-col :span="2">
              <el-button type="danger" @click="beforeBanBlogFormVisible = true">封禁/解禁用户</el-button>
            </el-col>
    </el-row>
    <!--    表格展示数据-->
    <el-table :data="tableBlogData" table-layout="fixed" border fit stripe>
      <!--      <el-table-column prop="id" label="序号" width="80px"/>-->
      <el-table-column type="index" width="80px"/>
      <el-table-column label="封面" width="80px" slot-scope="scope">
        <template #default="scope">
          <el-avatar
              :src="scope.row.userIcon"
              style="width: 50px;height: 50px"
          />
        </template>
      </el-table-column>
      <!--      <el-table-column prop="author" label="作者"/>-->
<!--      <el-table-column prop="userId" label="用户id" />-->
      <el-table-column prop="userNickname" label="用户昵称" />
      <el-table-column prop="userStatus" label="用户状态" />
      <el-table-column prop="title" label="文章标题"/>
      <!--      <el-table-column prop="coverImage" label="封面"/>-->
      <!--      <el-table-column prop="content" label="内容" width="100px"/>-->
      <el-table-column prop="isLike" label="收藏" />
      <el-table-column prop="commentsNum" label="评论数" />
      <el-table-column prop="likedNum" label="点赞数" />
      <el-table-column prop="isban" label="文章状态"/>
      <el-table-column prop="createTime" label="发布时间" />
      <el-table-column prop="updateTime" label="更新时间" />


      <el-table-column fixed="right" label="操作" width="120px" slot-scope="scope">
        <template #default="scope">
<!--          <el-button type="primary" :icon="Edit" circle @click="getBlogInfo(scope.row.id)"/>-->
          <el-button type="danger" :icon="Delete" circle @click="confirmDelete(scope.row.id)" />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :background="true"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
    />
    <el-dialog v-model="addUserFormVisible" title="添加用户" width="40%" center>
      <el-form :model="addBlogForm" :rules="addBlogFormRoles">
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="addBlogForm.title" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth" prop="content">
          <el-input v-model="addBlogForm.content" autocomplete="off"/>
        </el-form-item>
<!--        <el-form-item label="手机号" :label-width="formLabelWidth">-->
<!--          <el-input v-model="addBlogForm.phone" autocomplete="off"/>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addUserFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddBlog">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="beforeBanBlogFormVisible" title="请输入要封禁/解禁的文章ID" width="40%">
      <el-form :model="beforeBanBlogForm">
        <el-form-item label="文章id">
          <el-input v-model="beforeBanBlogForm.id" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="beforeBanBlogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="searchBlog(beforeBanBlogForm.id)">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="blogInfoFormVisible" width="20%" title="确认用户">
      <el-card :body-style="{ padding: '0px' }">
        <img
            :src="searchedBlog.images"
            class="image"
        />
      <div style="padding: 14px">
        <span>标题:{{ searchedBlog.title }}</span><br/>
        <span>内容:{{ searchedBlog.content }}</span>
      </div>
      </el-card>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="blogInfoFormVisible = false">取消</el-button>
        <el-button type="danger" @click="banBlog(beforeBanBlogForm.id)">
          封禁/解禁
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="updateBlogFormVisible" title="更新用户" width="40%" center>
      <el-form :model="updateBlogForm">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="updateBlogForm.username" autocomplete="off" disabled/>
        </el-form-item>
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="updateBlogForm.title" autocomplete="off" disabled/>
        </el-form-item>
        <el-form-item label="文章内容" :label-width="formLabelWidth">
          <el-input v-model="updateBlogForm.content" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="用户状态" :label-width="formLabelWidth">
          <el-select
              v-model="genderValue"
              placeholder="性别"
              style="width: 240px"
          >
            <el-option
                v-for="item in genderValueOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否为管理员" :label-width="formLabelWidth">
          <el-switch v-model="isAdmin" active-value="1" inactive-value="0"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="updateBlogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateBlog">
          提交
        </el-button>
      </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

.image {
  width: 100%;
  display: block;
}
</style>
